package io.rehuo.modules.app.controller;


import io.rehuo.common.utils.R;
import io.rehuo.common.validator.ValidatorUtils;
import io.rehuo.modules.app.entity.UserEntity;
import io.rehuo.modules.app.form.LoginForm;
import io.rehuo.modules.app.service.CommonService;
import io.rehuo.modules.app.service.UserService;
import io.rehuo.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private JwtUtils jwtUtils;


    @GetMapping("getCode")
    @ApiOperation("获取验证码")
    @ApiImplicitParam(name = "cmnd", value = "电话号码", paramType = "query", required = true, dataTypeClass = String.class)
    public R getCode(@RequestParam String cmnd) {
        commonService.getCode(cmnd);
        return R.ok("Gửi thành công");
    }

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);
        //后面加入秘钥验证账号

        //用户登录
        UserEntity userEntity = userService.login(form);

        //生成token
        String token = jwtUtils.generateToken(userEntity.getUserId());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("userEntity", userEntity);

        return R.ok(map);
    }


}
